package pers.vinsonws.jianghu.serverspring.session;

import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @auther vinsonws
 * @date 2018/11/4 18:45
 */
@Component
public class SessionManager {

    public static AttributeKey<NetSession> SESSION_KEY = AttributeKey.valueOf("session");


    public static boolean addSession(Channel channel, NetSession session) {
        Attribute<NetSession> sessionAttr = channel.attr(SESSION_KEY);//本质是将其存储在channel上
        return sessionAttr.compareAndSet(null, session);
    }

    public static NetSession getSession(Channel channel) {
        Attribute<NetSession> sessionAttr = channel.attr(SESSION_KEY);
        return sessionAttr.get() ;
    }

    public static String getIp(Channel channel) {
        return ((InetSocketAddress)channel.remoteAddress()).getAddress().toString().substring(1);
    }
}
